<template>
  <div class="article-category">
    <h1>文章分类</h1>
    <el-table :data="categories" style="width: 100%">
      <el-table-column prop="name" label="分类名称" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" @click="handleAdd" style="margin-top: 20px">添加分类</el-button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCategoryListService,
  addCategoryService,
  updateCategoryService,
  deleteCategoryService
} from '@/api/article'

const categories = ref([])
const loading = ref(false)

onMounted(() => {
  fetchCategories()
})

// 获取分类列表
const fetchCategories = async () => {
  try {
    loading.value = true
    const res = await getCategoryListService()
    categories.value = res.data
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 编辑分类
const handleEdit = (category) => {
  ElMessageBox.prompt('请输入分类名称', '编辑分类', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: category.name
  }).then(async ({ value }) => {
    if (!value) {
      ElMessage.warning('分类名称不能为空')
      return
    }
    try {
      await updateCategoryService({ id: category.id, name: value })
      const index = categories.value.findIndex(item => item.id === category.id)
      categories.value[index].name = value
      ElMessage.success('修改成功')
    } catch (error) {
      ElMessage.error('修改分类失败')
    }
  })
}

// 删除分类
const handleDelete = (category) => {
  ElMessageBox.confirm('确定删除该分类吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCategoryService(category.id)
      categories.value = categories.value.filter(item => item.id !== category.id)
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除分类失败')
    }
  })
}

// 添加分类
const handleAdd = () => {
  ElMessageBox.prompt('请输入分类名称', '添加分类', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async ({ value }) => {
    if (!value) {
      ElMessage.warning('分类名称不能为空')
      return
    }
    try {
      const res = await addCategoryService({ name: value })
      categories.value.push(res.data)
      ElMessage.success('添加成功')
    } catch (error) {
      ElMessage.error('添加分类失败')
    }
  })
}
</script>

<style scoped>
.article-category {
  padding: 20px;
}
</style>